import React, { useEffect, useMemo, useState, useRef } from "react";
import { FormSelect, ResultWrap } from "@/components";
import ReactEcharts from "echarts-for-react";

export default function EchartsCom(props) {
  const { loading, data = [], echartData = {}, optionFn } = props;

  const echartRef = useRef(null);
  const [currentData, setCurrentData] = useState({});

  useEffect(() => {
    setCurrentData(echartData);
  }, [JSON.stringify(echartData)]);

  const option = useMemo(() => optionFn(currentData), [optionFn, currentData]);

  return (
    <div className="echart-com-container">
      <div className="title-header">
        <a className="file-name" target="_blank" href={currentData.file_path} download>
          {currentData.file_name || "-"}
        </a>
        <FormSelect
          className="select-box"
          placeholder="切换其他文件"
          options={data}
          allowClear={false}
          value={currentData.id}
          onChange={(v) => {
            const item = data.find((item) => item.id === v);
            setCurrentData(item);
          }}
          fieldNames={{ value: "id", label: "file_name" }}
        />
      </div>
      <div className="echart-body">
        <ResultWrap ajaxLoad={loading} nodata={!echartData?.data?.length}>
          <ReactEcharts
            ref={echartRef}
            option={option}
            style={{ height: "100%", width: "100%" }}
          />
        </ResultWrap>
      </div>
    </div>
  );
}
